"use strict";

/**
 * @ngdoc function
 * @name jgappApp.controller:AttendanceIndexCtrl
 * @description
 * # AttendanceIndexCtrl
 * Controller of the jgappApp
 */
angular
  .module("jgappApp")
  .controller(
    "AttendanceIndexCtrl",
    function (
      $location,
      $interval,
      $timeout,
      DataService,
      openApi,
      localStorageService,
      MapService,
      Util
    ) {
      var vm = this;
      vm.options = [];
      this.checkinfo = {};
      this.checkinfo.today = new Date();
      this.goAttendancelist = function () {
        $location.path("attendance/attendance_list");
      };
      // 上班打卡
      this.checksign = function () {
        var param = {};
        param.deviceToken = NativeUtil.use("getDeviceInfo").deviceId;
        if (!param.deviceToken) {
          return;
        }
        param.acId = vm.checkinfo.acId;
        param.logTime = vm.checkinfo.logTime;
        param.overTime = vm.checkinfo.overTime;
        param.signType = vm.checkinfo.signType;
        //  0-范围外 1-正常 2-迟到 3-早退 默认传1，当不在打卡距离内需要传值0 并输入理由
        param.logType = 1;
        MapService.getcurPositon().then(function (data) {
          var curPoint = data;
          var attPoint = {};
          var ifPermission;
          attPoint.latitude = vm.checkinfo.lat;
          attPoint.longitude = vm.checkinfo.lng;
          param.distance = MapService.getDistance(attPoint, curPoint);
          // 根据经纬度获取地址
          param.lat = curPoint.latitude;
          param.lng = curPoint.longitude;
          param.address = curPoint.address + curPoint.describe;
          // 获取手机型号
          var deviceInfo = NativeUtil.use("getDeviceInfo");
          param.phoneModel =
            deviceInfo.manufacturer || "" + " " + deviceInfo.model;
          ifPermission = MapService.permissionDistance(
            attPoint,
            curPoint,
            vm.checkinfo.offSet
          );
          // 是否连接到了公司wifi
          vm.wifiInfo = NativeUtil.use("getConnectionInfo");
          if (
            vm.wifiInfo &&
            vm.checkinfo.wifiConfigMap &&
            vm.checkinfo.wifiConfigMap[vm.wifiInfo.mac]
          ) {
            param.wifiName = vm.checkinfo.wifiConfigMap[vm.wifiInfo.mac];
          }
          // 判断是否可以打卡
          // 如果设置wifi打卡，并且连接，可以打卡，没有连接就是外勤
          // 如果没有设置wifi打卡则判断是否连接
          // 如果是wifi打卡或者到了可以打卡的地点
          var wifiSign = false;
          if (param.wifiName) {
            wifiSign = true;
          } else if (ifPermission) {
            if (vm.checkinfo.clockWay == 1) {
              wifiSign = false;
            } else {
              wifiSign = true;
            }
          }
          if (wifiSign) {
            // 如果拍照打卡
            if (vm.checkinfo.clockWithSelfie == 1) {
              NativeUtil.use(
                "choosePhoto",
                function (data) {
                  param.attachment = data;
                  vm.submitSign(param);
                },
                {
                  num: 1,
                  type: 2,
                }
              );
            } else {
              vm.submitSign(param);
            }
          } else {
            // 外勤，去到外勤页面
            param.logType = 0;
            Util.saveLocalInfo("attParam", param);
            $location.path("attendance/attendance_outside");
          }
        });
      };

      // 提交考勤
      this.submitSign = function (param) {
        // 打卡
        DataService.getData(openApi.punchClock, param).then(function (data) {
          // 没有迟到
          // 1：正常，说明打卡成功，此时result 为当前的打卡时间，直接更新
          // -1：不正常，说明打卡不成功，此时提示result
          // 2：说明迟到了，此时弹出输入框，输入迟到理由，再次提交的时候设置logType=2
          // 3：说明早退了，此时弹出输入框，输入早退理由，再次提交的时候设置logType=3
          if (data.code == -1) {
            Util.Toast(data.result);
          } else if (data.code == 1) {
            vm.checkinfo = data.result;
            navigator.notification.beep(1);
            Util.Toast("打卡成功");
            localStorageService.set("checkinfo", data.result);
          } else if (data.code == 2) {
            // 迟到，补充理由
            param.logType = 2;
            Util.saveLocalInfo("attParam", param);
            $location.path("attendance/attendance_late/late");
          } else if (data.code == 3) {
            // 早退，补充理由
            param.logType = 3;
            Util.saveLocalInfo("attParam", param);
            $location.path("attendance/attendance_late/early");
          }
        });
      };
      // 考勤统计页面
      this.goStatisticlist = function () {
        $location.path("attendance/attendance_statisticDetail");
      };
      // 切换加班状态
      this.switchOvertime = function () {
        DataService.getData(openApi.changeOvertime).then(function (data) {
          vm.checkinfo = data;
        });
      };
      // 获取打卡信息
      vm.getCheckInfo = function () {
        getCheckInfo();
        refreshLocationInfo();
        Util.Toast("考勤以及位置信息刷新成功");
      };

      // 获取打卡信息
      var getCheckInfo = function () {
        DataService.getData(openApi.getAttendanceStatus, {
          acId: vm.acId,
        }).then(function (data) {
          vm.checkinfo = data;
          vm.wifiInfo = NativeUtil.use("getConnectionInfo");
          if (
            vm.wifiInfo &&
            vm.checkinfo.wifiConfigMap &&
            vm.checkinfo.wifiConfigMap[vm.wifiInfo.mac]
          ) {
            vm.iswifi = true;
          }
          localStorageService.set("checkinfo", data);
        });
      };
      var refreshLocationInfo = function () {
        // $timeout.cancel(vm.timer);
        NativeUtil.use("getLatLng", function (positon) {
          if (positon) {
            var positonJson = JSON.parse(positon);
            vm.address = positonJson.address + positonJson.describe;
          }
          // vm.timer = $timeout(function () {
          //     refreshLocationInfo()
          // }, 10000);
        });
      };

      var initDate = function () {
        vm.currentDate = new Date();
        $interval(function () {
          vm.currentDate = new Date();
        }, 10000);
      };

      var getAttConfig = function (fn) {
        let localAttId = localStorageService.get("attId");
        return DataService.getData(openApi.attConfig).then(function (config) {
          var options = Object.keys(config || {}).map(function (key) {
            return {
              label: config[key].address,
              value: key,
            };
          });
          if (options.length > 0) {
            var current = options.find(function (item) {
              return item.value === localAttId;
            });
            var acId = current ? current.value : options[0].value;
            localStorageService.set("attId", acId);
            vm.options = options;
            vm.acId = acId;
          }
          fn();
        });
      };

      vm.changeAtt = function () {
        localStorageService.set("attId", vm.acId);
        getCheckInfo();
      };
      var init = function () {
        getAttConfig(getCheckInfo);

        initDate();
        refreshLocationInfo();
      };

      init();
    }
  );
